<!--
 * @页面名称:窗体模型
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="form-tab3">
    <!-- 按钮组 -->
    <div class="button-group">
      <el-tooltip class="box-item" placement="bottom-end">
        <template #content>
          <span>添加界面</span>
        </template>
        <el-button :disabled="BtnStatus[0]" :icon="FolderAdd" @click="add"></el-button>
      </el-tooltip>
      <el-tooltip class="box-item" placement="bottom-end">
        <template #content>
          <span>修改界面</span>
        </template>
        <el-button :disabled="BtnStatus[1]" :icon="Edit" @click="edit"></el-button>
      </el-tooltip>
      <el-tooltip class="box-item" placement="bottom-end">
        <template #content>
          <span>删除界面</span>
        </template>
        <el-button :disabled="BtnStatus[2]" :icon="Delete" @click="del"></el-button>
      </el-tooltip>
    </div>
    <!-- 表格模块 -->
    <stable :columns="tableSetting.EWcolumns" :data="tableSetting.EWTabledata" @rowClick="rowClick"></stable>
    <!-- 增加或者编辑弹出框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="55%" draggable>
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="窗体类型:" prop="EW_Type">
              <el-select v-model="formData.EW_Type">
                <el-option label="空" value="空"></el-option>
                <el-option label="档案收集" value="档案收集"></el-option>
                <el-option label="档案整理" value="档案整理"></el-option>
                <el-option label="档案保存" value="档案保存"></el-option>
                <el-option label="档案利用" value="档案利用"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="说明:" prop="EW_Remark">
              <el-input v-model="formData.EW_Remark" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名:" prop="EW_FieldName">
              <el-input v-model="formData.EW_FieldName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指定值:" prop="EW_FieldValue">
              <el-input v-model="formData.EW_FieldValue" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作流描述:" prop="EW_Describe">
              <el-input v-model="formData.EW_Describe" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end">
          <el-col :span="24">
            <el-form-item label="窗体代码:" prop="EW_Det">
              <div class="cm-container">
                <codemirror v-model:value="formData.EW_Det" :tabSize="2" :options="editorOption" :height="370"></codemirror>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="preview">预览</el-button>
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 预览窗体 -->
    <el-dialog destroy-on-close v-model="previewSetting.visible" :title="previewSetting.title" width="55%" class="previewModel">
      <el-card>
        <div ref="selfForm" id="dynamic-modal"></div>
      </el-card>
      <!-- <div v-if="errList">
        {{ errList }}
      </div>
      <div v-else style="margin: 15px 0">
        {{ modalFormData }}
      </div> -->
    </el-dialog>
  </div>
</template>

<script lang="tsx">
import { reactive, ref, nextTick, defineComponent, createApp } from "vue";
import { FolderAdd, Edit, Delete } from "@element-plus/icons-vue";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import type { FormRules, FormInstance } from "element-plus";
import ElementPlus from "element-plus";
import SInput from "@/components/SInput.vue";
import SSelect from "@/components/SSelect.vue";
import TreeSelect from "@/components/STree.vue";
import VXETable from "vxe-table";
import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";
// 自动刷新(防止codemirror需要手动刷新才出数据)
import "codemirror/addon/display/autorefresh";
import Upload from "@/components/Upload/Img.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useUserStore } from "@/stores/modules/user";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useGlobalStore } from "@/stores/modules/global";
import { storeToRefs } from "pinia";
import { transTree } from "@/utils/util";
import ACrypto from "@/utils/crypto";
export default defineComponent({
  components: { Codemirror },
  setup() {
    const { proxy } = useCurrentInstance();
    const userStore = useUserStore();
    const dictionryStore = useDictionryStore();
    // 按钮状态
    const BtnStatus = ref([false, true, true]);
    // 表格配置
    const tableSetting = reactive({
      EWcolumns: [
        {
          type: "expand",
          width: 80,
          slots: {
            content: ({ row }: any) => {
              return [<pre>{ACrypto.getSS(row.EW_Det)}</pre>];
            }
          }
        },
        { title: "窗体类型", field: "EW_Type", sortable: true },
        { title: "说明", field: "EW_Remark", sortable: true }
      ],
      EWTabledata: [] as any[],
      sourthTableData: [] as any[] //源数据
    });
    // 弹出框配置
    const dialogSetting = reactive({
      visible: false,
      title: ""
    });
    // 预览窗体配置
    const previewSetting = reactive({
      visible: false,
      title: "预览窗体"
    });
    const errList = ref("");
    // 表单绑定字段
    const formData = ref({
      EW_Remark: "",
      EW_FieldName: "",
      EW_FieldValue: "",
      EW_Type: "",
      EW_Describe: "",
      EW_Det: ""
    });
    // 表格单击保存对象
    const rowClickObj = ref();
    // 父级主表点击保存对象
    const tabClickFromParent = ref();
    // 定义表单实例
    const formRef = ref<FormInstance>();
    // 表单字段规则
    const rules = reactive<FormRules>({});
    // 代码编辑框配置
    const editorOption = reactive({
      autorefresh: true,
      tabSize: 2,
      mode: "text/javascript",
      // theme: "ayu-mirage",
      line: true,
      viewportMargin: Infinity, //处理高度自适应时搭配使用
      highlightDifferences: true,
      autofocus: false,
      indentUnit: 2,
      smartIndent: true,
      readOnly: false, // 只读
      showCursorWhenSelecting: true,
      firstLineNumber: 1
    });
    // 获取表格数据
    const getTableData = (record: any) => {
      if (record) {
        tabClickFromParent.value = record;
        proxy.$vueAxios
          .post("Master_Base_EditorWindow/GetConditional", {
            order: "EW_Order asc",
            dtoList: [{ fieldName: "FMT_ID", fieldValue: record.FMT_ID }]
          })
          .then((res: any) => {
            tableSetting.EWTabledata = res.List;
          });
      }
    };
    // 点击表格
    const rowClick = ({ row }: any) => {
      rowClickObj.value = row;
      BtnStatus.value[1] = false;
      BtnStatus.value[2] = false;
    };
    // 新增
    const add = () => {
      dialogSetting.visible = true;
      dialogSetting.title = "新增";
      formRef.value?.resetFields();
    };
    // 修改
    const edit = () => {
      dialogSetting.visible = true;
      dialogSetting.title = "修改";
      nextTick(() => {
        formData.value = Object.assign({}, rowClickObj.value);
        formData.value.EW_Det = ACrypto.getSS(formData.value.EW_Det);
      });
    };
    // 删除
    const del = () => {
      proxy.$messageBox
        .confirm("确定删除该数据？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          proxy.$vueAxios.post("Master_Base_EditorWindow/Delete", [rowClickObj.value.EW_ID]).then((res: any) => {
            if (res.Mark) {
              getTableData(tabClickFromParent.value);
              proxy.$message.success("删除成功");
            } else {
              proxy.$message.error("删除失败");
            }
          });
        })
        .catch(err => {
          console.log(err);

          proxy.$message("取消删除");
        });
    };
    // 预览
    const preview = () => {
      previewSetting.visible = true;
      nextTick(() => {
        getDynamicDom(formData.value.EW_Det);
      });
    };
    // 获取动态窗体内容
    const getDynamicDom = (htmlCode: string) => {
      try {
        // 创建实例
        const app = createApp({
          components: {
            SInput,
            TreeSelect,
            Upload,
            SSelect
          },
          setup() {
            const globalStore = useGlobalStore();
            const { continuousSubmission } = storeToRefs(globalStore);
            // 预览窗体绑定字段
            const modalFormData = reactive({});
            // 表单字段规则
            const formRules = reactive<FormRules>({});
            // 按钮加载字段
            const submitLoading = ref(false);
            // 连续新增按钮加载字段
            const submitLoading2 = ref(false);
            // 数据
            const userConfig = reactive({});
            // 人员信息
            const PersonData = userStore.userList;
            // 字典数据
            const dictionary = dictionryStore.getDictionaryObj; //字典数据
            // 取消事件
            const cancel = () => {
              console.log("关闭");
            };
            // 确认事件
            const onSubmit = () => {
              console.log(modalFormData);
            };
            // 连续新增确认事件
            const onSubmit2 = () => {
              console.log(modalFormData);
            };
            // 失焦
            const changeTrigger = (fieldName: string) => {
              console.log("表单触发属性", fieldName);
            };
            return {
              continuousSubmission,
              modalFormData,
              formRules,
              submitLoading,
              submitLoading2,
              dictionary,
              userConfig,
              // dictionaryObj,
              PersonData,
              transTree,
              cancel,
              onSubmit,
              onSubmit2,
              changeTrigger
            };
          },
          template: htmlCode
        });
        // 引入icon
        for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
          app.component(key, component);
        }
        app.use(VXETable);
        app.use(ElementPlus); // 需要手动再次引入，不然识别不到组件
        app.mount("#dynamic-modal"); // 挂载实例
      } catch (err: any) {
        errList.value = err;
      }
    };
    // 确认事件
    const handle = () => {
      formRef.value!.validate((isValid: boolean) => {
        if (isValid) {
          if (dialogSetting.title === "新增") {
            const params = {
              eW_ID: proxy.$global.createID(),
              fmT_ID: tabClickFromParent.value.FMT_ID,
              eW_Type: formData.value.EW_Type,
              eW_Det: ACrypto.setSS(formData.value.EW_Det),
              eW_Enable: true,
              eW_FieldName: formData.value.EW_FieldName,
              eW_FieldValue: formData.value.EW_FieldValue,
              eW_Describe: formData.value.EW_Describe,
              eW_Create_By: userStore.userInfo.U_ID,
              eW_Update_By: userStore.userInfo.U_ID,
              eW_Remark: formData.value.EW_Remark
            };
            proxy.$vueAxios.post("Master_Base_EditorWindow", params).then((res: any) => {
              dialogSetting.visible = false;
              getTableData(tabClickFromParent.value);
            });
          } else {
            const params = {
              eW_ID: rowClickObj.value.EW_ID,
              fmT_ID: rowClickObj.value.FMT_ID,
              eW_Type: formData.value.EW_Type,
              eW_Det: ACrypto.setSS(formData.value.EW_Det),
              eW_Enable: rowClickObj.value.EW_Enable,
              eW_FieldName: formData.value.EW_FieldName,
              eW_FieldValue: formData.value.EW_FieldValue,
              eW_Describe: formData.value.EW_Describe,
              eW_Create_By: rowClickObj.value.U_ID,
              eW_Update_By: rowClickObj.value.U_ID,
              eW_Remark: formData.value.EW_Remark
            };
            proxy.$vueAxios.put("Master_Base_EditorWindow", params).then((res: any) => {
              dialogSetting.visible = false;
              getTableData(tabClickFromParent.value);
            });
          }
        }
      });
    };
    return {
      FolderAdd,
      Edit,
      Delete,
      BtnStatus,
      tableSetting,
      dialogSetting,
      previewSetting,
      errList,
      formData,
      formRef,
      rules,
      editorOption,
      rowClick,
      add,
      edit,
      del,
      preview,
      getTableData,
      handle
    };
  }
});
</script>

<style scoped lang="scss">
.form-tab3 {
  height: calc(100% - 40px);
  .button-group {
    margin: 0 0 10px;
  }
  .cm-container {
    width: 100%;
  }
  :deep(.previewModel) {
    .form_box {
      display: flex;
      max-height: calc(100vh - 95px);
      .form_left {
        width: 50%;
        overflow-y: auto;
      }
      .form_right {
        width: 50%;
        overflow-y: auto;
      }
      .el-date-editor {
        .el-input__wrapper {
          width: -webkit-fill-available;
        }
      }
    }
    .el-dialog__body {
      padding: 0;
    }

    // padding-bottom: 15px;
    .button {
      .el-form-item__content {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  :deep(.el-card__body) {
    padding: 0;
  }
}
:deep(.button) {
  padding: 24px;
}
:deep(.form) {
  max-height: 500px;
  padding: 24px;
  overflow: auto;
}
</style>
